package com.soup.lab.basic.efficiency;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

public class VariableTestCase {

    private static final Logger logger = LoggerFactory.getLogger(VariableTestCase.class);

    A a = new A();

    @Test
    public void test() {
        timing(() -> {
            for (int i = 0; i < 1_000_000_000; i++) {
                a.i++;
            }
        });
    }

    @Test
    public void test2() {
        timing(() -> {
            int j = a.i;
            for (int i = 0; i < 1_000_000_000; i++) {
                j++;
            }
            a.i = j;
        });
    }

    static A b = new A();

    @Test
    public void test3() {
        timing(() -> {
            for (int i = 0; i < 1_000_000_000; i++) {
                b.i++;
            }
        });
    }

    static class A {
        private int i;
    }


    private static <T> T timing(Supplier<T> execution) {
        long start = System.currentTimeMillis();
        try {
            return execution.get();
        } finally {
            logger.debug("costs: {} ms", System.currentTimeMillis() - start);
        }
    }

    private static void timing(String taskName, Runnable runnable) {
        long start = System.currentTimeMillis();
        try {
            runnable.run();
        } finally {
            logger.debug("[{}]|costs: {} ms", taskName, System.currentTimeMillis() - start);
        }
    }

    private static void timing(Runnable runnable) {
        long start = System.currentTimeMillis();
        try {
            runnable.run();
        } finally {
            logger.debug("costs: {} ms", System.currentTimeMillis() - start);
        }
    }
}
